""" 4 串口通讯 """
# https://learn.adafruit.com/circuitpython-essentials/circuitpython-uart-serial

import board
import busio
import digitalio


led = digitalio.DigitalInOut(board.LED)
led.direction = digitalio.Direction.OUTPUT

uart = busio.UART(board.TX, board.RX, baudrate=115200)

print("start: ", end="")
ret = uart.write(b"start")
print(ret)

uart.reset_input_buffer()

count = 0
while True:
    data = uart.readline()

    if data is not None:
        count += 1
        led.value = True

        # convert bytearray to string
        data_string = ''.join([chr(b) for b in data])
        print("%d receive[%d]: %s" % (count, len(data_string), data_string), end="")

        print("response to uart: ", end="")
        ret = uart.write(b"receive: "+data)
        print(ret)

        led.value = False

